package com.bootdo.clouddo.core.security;

import com.bootdo.clouddo.utils.StringUtils;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AjaxAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean
{
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException, ServletException
	{

		String callback = request.getParameter("callback");
		String fn = request.getParameter("fn");
		String jsonp = "";
		if (StringUtils.isNotEmpty(callback))
		{
			jsonp = callback;
		} else if (StringUtils.isNotEmpty(fn))
		{
			jsonp = fn;
		}
		try
		{
			if ("".equals(jsonp))
			{
				ObjectMapper objectMapper = new ObjectMapper();
				response.setHeader("Content-Type", "application/json;charset=UTF-8");
				JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(response.getOutputStream(), JsonEncoding.UTF8);
				FailHandlerInfo failInfo = new FailHandlerInfo();
				failInfo.setDesc(ex.getMessage());
				failInfo.setLogined(false);
				objectMapper.writeValue(jsonGenerator, failInfo);
			} else
			{
				String rslt = jsonp + "({\"logined\":\"false\", \"desc\":\"" + ex.getMessage() + "\"})";
				response.getWriter().write(rslt);
				response.flushBuffer();
			}
		} catch (JsonProcessingException e)
		{
			throw new HttpMessageNotWritableException("Could not write JSON: " + e.getMessage(), e);
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception
	{
		// TODO Auto-generated method stub

	}

}
